package com.lsl.gulimall.auth.service.impl;

import com.lsl.common.constant.AuthConstant;
import com.lsl.common.utils.R;
import com.lsl.gulimall.auth.feign.MemberFeignService;
import com.lsl.gulimall.auth.feign.ThirdPartFeignService;
import com.lsl.gulimall.auth.service.LoginService;
import com.lsl.gulimall.auth.utils.RedisUtil;
import com.lsl.gulimall.auth.vo.LoginUserVo;
import com.lsl.gulimall.auth.vo.RegisterUserVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author Zed
 * @description
 * @date 2022/10/16 14:48
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public R sendCode(String phone) {
        String redisCodeKey = AuthConstant.SMS_CODE_CACHE_PREFIX + phone;
        //通过key去获取验证码code
        String redisCodeValue = redisUtil.get(redisCodeKey);
        if (StringUtils.isNotBlank(redisCodeValue)) {
            //防止重复刷
            long codeTime = Long.parseLong(redisCodeValue.split("_")[1]);
            long nowTime = System.currentTimeMillis();
            if (nowTime - codeTime < 60 * 1000) {
                return R.error(500, "获取验证码过快,请稍后再试");
            }
        }
        double random = Math.random();
        if (random > 0.1) {
            random = random * 10000;
        } else {
            random = random * 100000;
        }
        //redis中没有,调用发送验证码服务
        R r = thirdPartFeignService.sendCode(phone, String.valueOf((int) Math.floor(random)));
        if (r.getCode() == 0) {
            redisUtil.setEx(redisCodeKey, (int) Math.floor(random) + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return r;
        }
    }

    @Override
    public R validCode(RegisterUserVo registerUserVo) {
        String redisCodeKey = AuthConstant.SMS_CODE_CACHE_PREFIX + registerUserVo.getPhoneNum();
        //通过key去获取验证码code
        String redisCodeValue = redisUtil.get(redisCodeKey);
        if (StringUtils.isBlank(redisCodeValue)) {
            return R.error(500, "验证码无效");
        }

        if (redisCodeValue.split("_")[0].equals(registerUserVo.getCode())) {
            return memberFeignService.saveMember(registerUserVo);
        }
         return R.error(500, "验证码验证失败");
    }
}
